#include "MyPlugin.h"
#include <QWidget>
#include <QDebug>
#include <QtGui>
#include <QtCore/QTimer>
#include <QWidget>


#include <osg/Notify>
#include <osgViewer/CompositeViewer>
#include <osgEarthUtil/ExampleResources>
#include <osgEarthUtil/EarthManipulator>
#include <osgEarthQt/ViewerWidget>
#include <QApplication>
#include <QMainWindow>
#include <QStatusBar>
#include <QMdiArea>
#include <QMdiSubWindow>

#include <QPushButton>
#include <QLabel>
#include <QFile>

#include "module/EventEngine.h"

#ifdef Q_WS_X11
#include <X11/Xlib.h>
#endif


using namespace osgEarth;
using namespace osgEarth::Util;
using namespace osgEarth::QtGui;

int
usage( const std::string& msg )
{
    OE_NOTICE << msg << std::endl << std::endl;
    OE_NOTICE << "USAGE: osgearth_qt_simple file.earth" << std::endl;

    return -1;
}

MyPlugin::MyPlugin():BasePlugin(MYPLUGIN_NAME,
                                   MYPLUGIN_DESCRIPTION)
{
    AddType(PluginType::System);
    AddType(PluginType::CenterWidget);

}

void MyPlugin::OnLoad(int argc, char **argv)
{
    osg::ArgumentParser arguments(&argc,argv);
    if ( arguments.read("--stencil") )
        osg::DisplaySettings::instance()->setMinimumNumStencilBits(8);


    osgViewer::Viewer* viewer = new osgViewer::Viewer(arguments);
    viewer->setThreadingModel( viewer->SingleThreaded );
    viewer->setRunFrameScheme( viewer->ON_DEMAND );
    viewer->setCameraManipulator( new EarthManipulator() );

    // load an earth file
    osg::Node* node = MapNodeHelper().load(arguments, viewer);
    if ( !node )
        return;

    viewer->setSceneData( node );


#ifdef Q_WS_X11
    // required for multi-threaded viewer on linux:
    XInitThreads();
#endif

    mEarthWidget = new ViewerWidget( viewer );
    mEarthWidget->show();

//    QMainWindow* win = new QMainWindow;

//    win->setStyleSheet(loadQss(QApplication::applicationDirPath()+"/qss/main.qss"));

//    win->setCentralWidget( viewerWidget );
//    win->setGeometry(100, 100, 1024, 800);

//    win->statusBar()->showMessage(QString("Quite possibly the world's simplest osgEarthQt app."));


//    QPushButton* btn = new QPushButton("Button",win);
//    btn->move(0,0);

//    QLabel* lb = new QLabel("Label",win);
//    lb->move(0,100);

//    win->show();



}

void *MyPlugin::HandleEvent(Event event, void *pData, BasePlugin *pSender)
{
    switch (event) {
    case Event::EventBase:
    {
        qDebug() << "Recved pSender: " << pSender->GetName();
        break;
    }
    default:
        break;
    }

    return nullptr;
}

QWidget *MyPlugin::GetWidget()
{
    return mEarthWidget;
}

QString MyPlugin::loadQss(QString filepath)
{
    QFile file(filepath);
    if(!file.open(QIODevice::ReadOnly)){
        return "";
    }

    return file.readAll();
}
